var ws = require("nodejs-websocket");
console.log("开始建立连接...");

class User {
  constructor(name,sign,userGroup){
    this.name = name;
    this.sign = sign;
    this.userGroup = userGroup;
    this.userGroup.addUser(this);
  }
}
class Users {
  constructor(){
    this.users = [];
  }
  addUser(user){
    this.users.push(user)
  }
  sendAll(msg){
    this.users.forEach(item=>{
      this.sendMsg(item.sign,msg)
    })
  }
  sendMsg(user,msg){
    user.sendText(msg);
  }
}

class Info {
  sendInfo(id,msg){
    return JSON.stringify({id:id,type:0,msg:msg})
  }
  placingChess(id,msg){
    return JSON.stringify({id:id,type:1,msg:msg})
  }
}
var game1 = null,game2 = null , game1Ready = false , game2Ready = false;
let users = new Users();
let info = new Info();
let currentId = 0;
let match = []
var server = ws.createServer(function(conn){
    let user 
    conn.on("text", function (str) {
      
       let msg = JSON.parse(str)
       console.log(msg)
        if(msg.type == 0){
          let id = currentId
          user = new User(id,conn,users);
          currentId ++
          let sendmsg = info.sendInfo(currentId,"欢迎进入")
          conn.sendText(sendmsg);
          if(users.users.length > 1){
            users.sendAll(info.sendInfo('','已为你匹配到对手'));
          }
        }else{
          console.log(users.users)
          let id = msg.id - 1
          users.sendMsg(users.users[1-id].sign,info.placingChess(id,msg.data))
        }
    })
    conn.on("close", function (code, reason) {
        console.log("关闭连接")
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭")
    });
}).listen(8001)

console.log("WebSocket建立完毕")